package org.snusmumr.android.media;

import java.util.Formatter;

import org.snusmumr.android.media.data.DatabaseProvider;
import org.snusmumr.android.media.data.DatabaseProvider.DatabaseMode;
import org.snusmumr.android.media.data.DeleteMediaItemOperation;
import org.snusmumr.android.media.data.MediaColumns;
import org.snusmumr.android.media.data.UnlentItemsOperation;
import org.snusmumr.android.media.data.adapter.MediaListAdapter;
import org.snusmumr.android.media.data.adapter.MediaListAdapter.OnCheckedListener;
import org.snusmumr.android.media.util.Utils;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MediaList extends ListActivity {
	public static enum ParentType {
		Category, Labels
	}
//	private static final String TAG = MediaList.class.getSimpleName();
	
	private DatabaseProvider mDbProvider;
	private MediaListAdapter adapter;
	private Long parentId;
	private String parentName;
	private ParentType parentType;
	
	private OnItemClickListener itemClickedHandler = new OnItemClickListener() {
	    public void onItemClick(AdapterView<?> parent, View v, int position, long id)
	    {
	        editItem(id);
	    }
	};
	
	private OnCheckedListener itemCheckedListener = new OnCheckedListener() {
		@Override
		public void onChecked(boolean isChecked, int position) {
//			if(checkedCount > 0) 
//				showButtonsPanel();
//			else
//				hideButtonsPanel();
			getListView().setItemChecked(position, isChecked);
			int checkedCount = getListView().getCheckedItemIds().length;
			if(checkedCount > 0) 
				showButtonsPanel();
			else
				hideButtonsPanel();
		}
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.media_list);
		
		final Bundle extras = getIntent().getExtras();
		this.parentId = extras.getLong(Constants.KEY_PARENT_ID);
		this.parentName = extras.getString(Constants.KEY_PARENT_NAME);
		this.parentType = (ParentType) extras.get(Constants.KEY_PARENT_TYPE);
		
		// init top menu buttons
		View swichtParentBtn = findViewById(R.id.btn_media_list_parent_name);
		swichtParentBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				switchParent();
			}
		});
		
		View addItemBtn = findViewById(R.id.btn_media_list_add);
		addItemBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				addItem();
			}
		});
		
		mDbProvider = DatabaseProvider.getInstance(this);
		getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		getListView().setFocusable(false);
		getListView().setOnItemClickListener(itemClickedHandler);
		registerForContextMenu(getListView());
	}
	
	private void hideButtonsPanel() {
		View buttonsPanel = findViewById(R.id.lend_buttons_panel);
		if(buttonsPanel != null)
			buttonsPanel.setVisibility(View.INVISIBLE);
	}

	private void showButtonsPanel() {
		View buttonsPanel = findViewById(R.id.lend_buttons_panel);
		if(buttonsPanel == null) {
			buttonsPanel = ((ViewStub) findViewById(R.id.stub_lend_buttons_panel)).inflate();
			Button lendBtn = (Button) buttonsPanel.findViewById(R.id.btn_item_lend);
			Button unlendBtn = (Button) buttonsPanel.findViewById(R.id.btn_item_unlend);
			lendBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					hideButtonsPanel();
					
					final long[] itemsId = getListView().getCheckedItemIds();
					if(itemsId != null && itemsId.length > 0) {
						Intent intent = new Intent(MediaList.this, SelectContactForLendActivity.class);
				        intent.putExtra(Constants.KEY_ID, itemsId);
						startActivity(intent);
						
					}
				}
			});
			unlendBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					hideButtonsPanel();
					unlendItems();
				}
			});
		} else {
			buttonsPanel.setVisibility(View.VISIBLE);
		}
	}

	private void switchParent() {
		final Cursor cursor = mDbProvider.getDatabase(DatabaseMode.Read)
				.query(Constants.DB_TABLE_CATEGORY, 
				Constants.DB_COLUMNS_CATEGORY, 
				"_id <> ?", new String[]{parentId.toString()}, null, null, "name asc");
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		final String title = Utils.format(getResources(), R.string.media_list_switch_parent, getParentType());
		builder.setTitle(title).setCursor(cursor, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				cursor.moveToFirst();
				cursor.move(which);
				MediaList.this.parentId = cursor.getLong(0);
				MediaList.this.parentName = cursor.getString(1);
				cursor.close();
				loadData();
			}
		}, "name").setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				cursor.close();
			}
		}).show();
	}
	
	private String getParentType() {
		switch (parentType) {
		case Category:
			return getResources().getString(R.string.media_list_parent_category);

		case Labels:
			return getResources().getString(R.string.media_list_parent_label);
		default:
			break;
		}
		return "";
	}

	@Override
	protected void onPause() {
		super.onPause();
		Utils.closeCursor(adapter);
		mDbProvider.close();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		loadData();
	}


	private void loadData() {
		Button parentNameView = (Button) findViewById(R.id.btn_media_list_parent_name);
		parentNameView.setText(getParentType() + ":\n" + parentName);
		
		final Resources res = getResources();
		Cursor cursor;
		switch (parentType) {
		case Category:
			cursor = mDbProvider.getDatabase(DatabaseMode.Read)
				.rawQuery(res.getString(R.string.sql_fetch_items_by_category), new String[]{parentId.toString()});
			break;

		case Labels:
			cursor = mDbProvider.getDatabase(DatabaseMode.Read)
			.rawQuery(res.getString(R.string.sql_fetch_items_by_label), new String[]{parentId.toString()});
			break;
		default:
			cursor = null;
			break;
		}
		
		if(cursor != null) {
			adapter = new MediaListAdapter(this, cursor, mDbProvider.getDatabase(DatabaseMode.Read), itemCheckedListener);
			setListAdapter(adapter);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.media_list_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mn_media_list_add:
			addItem();
			return true;
		case R.id.mn_media_list_sort:
			Toast.makeText(this, "sort selected", Toast.LENGTH_SHORT).show();
			return true;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void addItem() {
		Intent intent = new Intent(this, MediaItemContent.class);
		intent.putExtra(Constants.KEY_PARENT_ID, parentId);
		startActivity(intent);
	}
	
	private void unlendItems() {
		new AlertDialog.Builder(MediaList.this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.confirm_unlend_title)
        .setMessage(R.string.confirm_unlend_msg)
        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            	final long[] itemsId = getListView().getCheckedItemIds();
            	Boolean unlent = new UnlentItemsOperation(MediaList.this, itemsId).execute();
            	if(Boolean.TRUE.equals(unlent))
            		loadData();
            }
        })
        .setNegativeButton(android.R.string.no, null)
        .show();
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if(v == getListView()) {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.items_context, menu);
			
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			Cursor c = (Cursor) adapter.getItem(info.position);
			String name = getItemFullName(c);
		    menu.setHeaderTitle(name);
		}
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	private String getItemFullName(Cursor c) {
		String name = c.getString(c.getColumnIndex(MediaColumns.AUTHOR_NAME)) + 
		" >> " + c.getString(c.getColumnIndex(MediaColumns.ITEM_NAME));
		return name;
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		Cursor c = (Cursor) adapter.getItem(info.position);
		String listItemName = getItemFullName(c);
		final long id = c.getLong(0);
		
		switch (item.getItemId()) {
		case R.id.men_item_delete:
			Resources res = getResources();
			final Formatter format = new Formatter();
			String message = format.format(res.getString(R.string.msg_sure_to_delete), listItemName).toString();
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(message).setCancelable(false)
			.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					boolean delete = new DeleteMediaItemOperation(MediaList.this, id).execute();
					if(delete)
						loadData();
				}
			}).setNegativeButton(android.R.string.no, null).show();
			return true;
		case R.id.men_item_edit:
			editItem(id);
			return true;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

	public void editItem(long id) {
		Intent intent = new Intent(MediaList.this, MediaItemContent.class);
		intent.putExtra(Constants.KEY_ID, id);
		intent.putExtra(Constants.KEY_PARENT_ID, parentId);
		startActivity(intent);
	}
}
